var feedParser = require('feedparser')
, http = require('http')
, url = require('url')
, crypo = require('crypto') 
, fs = require('fs')
, db = require('./db')
, utils = require('./utils')
, async = require('async')

function getKey(item) {
  try {
    var urlObj = url.parse(item.link, true);
    var redirectLink = urlObj.query.url;
    var redirectUrlObj = url.parse(redirectLink);
    var pathnames = redirectUrlObj.pathname.split('/');
    var filename = pathnames[pathnames.length - 1];
    return filename.split('.')[0];
  } catch (err) {
    var md5sum = crypo.createHash('md5');
    md5sum.update(item.title);
    return md5sum.digest('hex');
  }
}

function getjson(request, response, render) {
  var feedMeta;
  var episodes = [];
  var url = 'http://rss.sina.com.cn/news/society/focus15.xml';
  http.get(
    url,
    function(res) {
        res.pipe(new feedParser({}))
            .on('error', function(error){
                utils.responseError(
                    response, 
                    400, 
                    error
                );
            })
            .on('meta', function(meta){
                // Store the metadata for later use
                feedMeta = meta;
            })
            .on('readable', function(){
                var stream = this;
                var item;
                while (item = stream.read()){
                    // Each 'readable' event will contain 1 article
                    // Add the article to the list of episodes
                    var key = getKey(item);
                    var ep = {
                        'title': item.title,
                        'link': item.link,
                   			'summary' : item.summary,
                        'pubdate': item.pubDate,
                        'key' : key,
                    };
                    episodes.push(ep);
                }                    
            })
            .on('end', function(){
                async.parallel(
                    [
                        async.apply(db.saveFeed, episodes),
                        async.apply(
                            async.waterfall,
                            [
                                utils.addSpeechLinks(request, episodes),
                                function(eps, cb) {
                                    var result = {
                                        'title': feedMeta.title,
                                        'link': feedMeta.link,
                                        'image': {
                                            'url': feedMeta.image.url,
                                        },
                                        'episodes': eps
                                    };
                                    render(request, response, result);
                                    cb(null);
                                }
                            ]
                        )
                    ]
                );
            });
    }
  );
}

module.exports = {
  getjson: getjson
}
